package com.xmy.cultivate.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.xmy.cultivate.annotaion.RepeatSubmit;
import com.xmy.cultivate.entity.BookExcludeSubscription;
import com.xmy.cultivate.entity.BookFetch;
import com.xmy.cultivate.entity.BookStudent;
import com.xmy.cultivate.mapper.QuarterMapper;
import com.xmy.cultivate.service.IBookExcludeSubscriptionService;
import com.xmy.cultivate.service.IBookFetchService;
import com.xmy.cultivate.service.IBookOrderService;
import com.xmy.cultivate.service.IBookStudentService;
import com.xmy.cultivate.util.Code;
import com.xmy.cultivate.util.CommonUtil;
import com.xmy.cultivate.util.IdWorker;
import com.xmy.cultivate.util.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.web.bind.annotation.*;
import org.springframework.stereotype.Controller;

import java.util.List;

/**
 * <p>
 * 教材领取 前端控制器
 * </p>
 *
 * @author hpiggy
 * @since 2025-01-05
 */
@RestController
@RequestMapping("/api/bookFetch")
@Scope("prototype")
public class BookFetchController extends BaseController {
    @Autowired
    IBookFetchService iBookFetchService;

    @Autowired
    IBookStudentService iBookStudentService;

    @Autowired
    IBookExcludeSubscriptionService iBookExcludeSubscriptionService;

    @Autowired
    IdWorker idWorker;

    /**
     * @param yearPart
     * @param quarterNum
     * @param subjectsId
     * @param classTypeId
     * @param lessonType
     * @param type        1是列表，2是详情
     * @param fetchType   1已领取，0未领取
     * @param status
     * @return
     */
    public Result fetchList(@RequestParam(value = "yearPart", required = false, defaultValue = "") Integer yearPart,
                            @RequestParam(value = "quarterNum", required = false, defaultValue = "") Integer quarterNum,
                            @RequestParam(value = "subjectsId", required = false, defaultValue = "") String subjectsId,
                            @RequestParam(value = "classTypeId", required = false, defaultValue = "") String classTypeId,
                            @RequestParam(value = "lessonType", required = false, defaultValue = "1") Integer lessonType,
                            @RequestParam(value = "type", required = false, defaultValue = "1") Integer type,
                            @RequestParam(value = "fetchType", required = false, defaultValue = "1") Integer fetchType,
                            @RequestParam(value = "status", required = false, defaultValue = "1") Integer status
    ) {
        return null;
    }


    /**
     * 领取教材
     *
     * @param bookFetch
     * @return
     */
    @PostMapping("/addBookFetch")
    //@RepeatSubmit(expireSeconds = 5)
    public Result addBookFetch(@RequestBody BookFetch bookFetch) {

//        QueryWrapper<BookStudent> studentQueryWrapper = new QueryWrapper<>();
//        studentQueryWrapper.eq("order_id", bookFetch.getOrderId());
//        studentQueryWrapper.eq("subjects_id", bookFetch.getSubjectsId());
//        studentQueryWrapper.eq("class_type_id", bookFetch.getClassTypeId());
//        studentQueryWrapper.eq("school_id", bookFetch.getSchoolId());
//        studentQueryWrapper.in("year_class_id", bookFetch.getYearClassIdList());
//        studentQueryWrapper.eq("status", 2);
//        if (bookFetch.getLessonNum() != null) {
//            studentQueryWrapper.eq("lesson_num", bookFetch.getLessonNum());
//        }
//        List<BookStudent> bookStudents = iBookStudentService.list(studentQueryWrapper);
//        if (bookStudents == null || bookStudents.size() == 0) {
//            return new Result(Code.EXP_ERROR, null, "没有需要领取的订单数据");
//        }

//        for (Integer yearClassId : bookFetch.getYearClassIdList()) {
//            QueryWrapper<BookFetch> queryWrapper = new QueryWrapper<>();
//            queryWrapper.eq("order_id", bookFetch.getOrderId());
//            queryWrapper.eq("subjects_id", bookFetch.getSubjectsId());
//            queryWrapper.eq("year_class_id", yearClassId);
//            queryWrapper.eq("class_type_id", bookFetch.getClassTypeId());
//            queryWrapper.eq("school_id", bookFetch.getSchoolId());
//            count = iBookFetchService.count(queryWrapper);
//            if (count > 0) {
//                return new Result(Code.EXP_ERROR, null, "该教材已领取,请勿重复领取");
//            }
//        }

//        boolean save = true;
//        for (Integer yearClassId : bookFetch.getYearClassIdList()) {
//            bookFetch.setCreatedId(this.adminId);
//            bookFetch.setYearClassId(yearClassId);
//            bookFetch.setId(null);
//            boolean saveTemp = iBookFetchService.save(bookFetch);
//            if (!saveTemp) {
//                save = saveTemp;
//            }
//        }
//        if (save) {
//            UpdateWrapper<BookStudent> updateWrapper = new UpdateWrapper<>();
//            updateWrapper.eq("order_id", bookFetch.getOrderId());
//            updateWrapper.eq("subjects_id", bookFetch.getSubjectsId());
//            updateWrapper.eq("class_type_id", bookFetch.getClassTypeId());
//            updateWrapper.in("year_class_id", bookFetch.getYearClassIdList());
//            updateWrapper.eq("school_id", bookFetch.getSchoolId());
//            updateWrapper.eq("status", 2);
//            if (bookFetch.getLessonNum() != null) {
//                updateWrapper.eq("lesson_num", bookFetch.getLessonNum());
//            }
//            updateWrapper.set("status", 3);//调整为校区已领取
//            iBookStudentService.update(updateWrapper);
//        } else {
//            return new Result(Code.ERROR, null, "领取失败");
//        }

        for (Integer yearClassId : bookFetch.getYearClassIdList()) {
            // 根据年级判断是否已经领取过
            QueryWrapper<BookStudent> bookStudenQueryWrapper = new QueryWrapper<>();
            bookStudenQueryWrapper.eq("order_id", bookFetch.getOrderId());
            bookStudenQueryWrapper.eq("subjects_id", bookFetch.getSubjectsId());
            bookStudenQueryWrapper.eq("class_type_id", bookFetch.getClassTypeId());
            bookStudenQueryWrapper.eq("school_id", bookFetch.getSchoolId());
            bookStudenQueryWrapper.eq("year_class_id", yearClassId);
            bookStudenQueryWrapper.eq("status", 2);
            if (bookFetch.getLessonNum() != null) {
                bookStudenQueryWrapper.eq("lesson_num", bookFetch.getLessonNum());
            }
            Long bookFetchCount = iBookStudentService.count(bookStudenQueryWrapper);

            if (bookFetchCount.equals(0L)) {
                // 没有未领取的数据，结束此次循环
                continue;
            }

            UpdateWrapper<BookStudent> updateWrapper = new UpdateWrapper<>();
            updateWrapper.eq("order_id", bookFetch.getOrderId());
            updateWrapper.eq("subjects_id", bookFetch.getSubjectsId());
            updateWrapper.eq("class_type_id", bookFetch.getClassTypeId());
            updateWrapper.eq("year_class_id", yearClassId);
            updateWrapper.eq("school_id", bookFetch.getSchoolId());
            updateWrapper.eq("status", 2);
            if (bookFetch.getLessonNum() != null) {
                updateWrapper.eq("lesson_num", bookFetch.getLessonNum());
            }
            updateWrapper.set("status", 3);//调整为校区已领取
            iBookStudentService.update(updateWrapper);

            // 判断是否已经添加过数据
            QueryWrapper<BookFetch> bookFetchQueryWrapper = new QueryWrapper<>();
            bookFetchQueryWrapper.eq("order_id", bookFetch.getOrderId());
            bookFetchQueryWrapper.eq("subjects_id", bookFetch.getSubjectsId());
            bookFetchQueryWrapper.eq("class_type_id", bookFetch.getClassTypeId());
            bookFetchQueryWrapper.eq("year_class_id", yearClassId);
            bookFetchQueryWrapper.eq("school_id", bookFetch.getSchoolId());
            Long count = iBookFetchService.count(bookFetchQueryWrapper);
            if (count.equals(0L)) {
                bookFetch.setCreatedId(this.adminId);
                bookFetch.setYearClassId(yearClassId);
                bookFetch.setId(idWorker.nextId());
                iBookFetchService.save(bookFetch);
            }
        }

        return new Result(Code.OK, null, "领取成功");
    }

    /**
     * 取消订购
     */
    @PostMapping("/cancelOrder")
    public Result cancelOrder(@RequestBody BookExcludeSubscription subscription) {

        if (subscription.getStudentIdList() != null && subscription.getStudentIdList().size() > 0) {
            for (Long studentId : subscription.getStudentIdList()) {
                subscription.setId(idWorker.nextId());
                subscription.setStudentId(studentId);
                iBookExcludeSubscriptionService.save(subscription);
            }
        }
        if (subscription.getTeacherIdList() != null && subscription.getTeacherIdList().size() > 0) {
            for (Long teacherId : subscription.getTeacherIdList()) {
                subscription.setId(idWorker.nextId());
                subscription.setTeacherId(teacherId);
                iBookExcludeSubscriptionService.save(subscription);
            }
        }

        return new Result(Code.OK, null, Code.SAVE_OK_MSG);
    }


    /**
     * 重新订购
     */
    @PostMapping("/againOrder")
    public Result againOrder(@RequestBody BookExcludeSubscription subscription) {
        if (subscription.getLessonType() == null) {
            subscription.setLessonType(1);
        }

        QueryWrapper<BookExcludeSubscription> wrapper = new QueryWrapper<>();
        if (subscription.getStudentIdList() != null && subscription.getStudentIdList().size() > 0) {
            wrapper.in("student_id", subscription.getStudentIdList());
        }
        if (subscription.getTeacherIdList() != null && subscription.getTeacherIdList().size() > 0) {
            wrapper.in("teacher_id", subscription.getTeacherIdList());
        }
        if (subscription.getLessonNum() != null) {
            wrapper.eq("lesson_num", subscription.getLessonNum());
        }
        wrapper.eq("year_class_id", subscription.getYearClassId());
        wrapper.eq("class_type_id", subscription.getClassTypeId());
        wrapper.eq("subjects_id", subscription.getSubjectsId());
        wrapper.eq("lesson_type", subscription.getLessonType());
        wrapper.eq("book_text_id", subscription.getBookTextId());
        wrapper.eq("book_text_type", subscription.getBookTextType());
        wrapper.eq("year_part", subscription.getYearPart());
        wrapper.eq("quarter_num", subscription.getQuarterNum());
        wrapper.eq("school_id", subscription.getSchoolId());
        iBookExcludeSubscriptionService.remove(wrapper);

        return new Result(Code.OK, null, Code.DELETE_OK_MSG);
    }

}
